package com.example.utils.cacheutils;

import com.example.model.CacheModel;

import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * @Classname CacheUtils
 * @Description TODO
 * @Date 2022/7/28 22:00
 * @Created by XiongXiong
 * @Author: X.I.O
 */
public class CacheUtils {

    private static Map<String, CacheModel> CACHE_MODEL;

    /**
     * 初始化缓存系统
     */
    private static void initCacheSystem(){
        if(CacheUtils.CACHE_MODEL==null){
            CacheUtils.CACHE_MODEL = new HashMap<>(1000);
        }
    }

    public static void put(String key,Object value,Integer expireNum){
        initCacheSystem();
        CacheModel cacheModel=cacheModelBuild(key,value,expireNum);
        CacheUtils.CACHE_MODEL.put(key,cacheModel);
    }

    public static void remove(String key){
        initCacheSystem();
        CacheModel cacheModel=CacheUtils.CACHE_MODEL.get(key);
        if(cacheModel!=null){
            CacheUtils.CACHE_MODEL.remove(key,cacheModel);
        }
    }

    public static Object get(String key){
        initCacheSystem();
        CacheModel cacheModel=CacheUtils.CACHE_MODEL.get(key);
        if(cacheModel == null){
            return null;
        }
        if(cacheModel.getExpireDate()==null){
            return cacheModel.getValue();
        }
        Date expireDate=cacheModel.getExpireDate();
        Date now=new Date();
        if(now.getTime()>= expireDate.getTime()){
            CacheUtils.CACHE_MODEL.remove(key,cacheModel);
            return null;
        }
        return cacheModel.getValue();
    }

    private static CacheModel cacheModelBuild(String key,Object value,Integer expireNum){
        CacheModel cacheModel=new CacheModel();
        cacheModel.setKey(key);
        cacheModel.setValue(value);
        Date date=new Date();
        if(expireNum!=null){
            Date expireDate=addDate(date,expireNum);
            cacheModel.setExpireDate(expireDate);
        }
        cacheModel.setCreteDate(new Date());
        return cacheModel;
    }

    private static Date addDate(Date date,Integer expireNum){
        Calendar cal = Calendar.getInstance();
        cal.setTime(date);
        cal.add(Calendar.SECOND,expireNum);
        return cal.getTime();
    }
}
